<template>
  <el-dialog
      :modal-value="dialogVisible"
      :title="dialogTitle"
      style="padding: 40px"
      width="600px"
      @close="handleClose"
      draggable
      overflow
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="用户名:" prop="username">
        <el-input v-model="form.username" :disabled="form.id===-1?false:'disabled'"/>
        <el-alert
            v-if="form.id===-1"
            title="默认初始密码：123456"
            :closable="false"
            style="line-height: 10px"
            type="success"></el-alert>
      </el-form-item>

      <el-form-item label="手机号:" prop="phone_number">
        <el-input v-model="form.phone_number"/>
      </el-form-item>

      <el-form-item label="邮箱:" prop="email">
        <el-input v-model="form.email"/>
      </el-form-item>

      <el-form-item label="状态:" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">正常</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注:" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="4"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确 认</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, watch} from 'vue'
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";

// const dialogVisible = ref(false)
const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  }
})

const form = ref({
  id: -1,
  username: '',
  password: '123456',
  status: 1,
  phone_number: '',
  email: '',
  remark: '',
})

const checkUsername = async (rule, value, callback) => {
  if (!value) return callback(new Error('用户名不能为空')) // 优先检查空值

  // 仅在新增模式时校验
  if (props.id === -1) {  // 使用props.id判断模式
    try {
      const res = await requestUtil.post('user/check', {username: value})
      if (res.data.code === 500) {
        callback(new Error('用户名已存在'))
      } else {
        callback()
      }
    } catch (e) {
      callback(new Error('校验服务异常'))
    }
  } else {
    callback()
  }
}

const rules = ref({
  username: [
    {required: true, message: '请输入用户名'},
    {validator: checkUsername, trigger: 'blur'}
  ],
  email: [
    {required: true, message: '邮箱地址不能为空', trigger: 'blur'}, {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  phone_number: [
    {required: true, message: '手机号码不能为空', trigger: 'blur'}, {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})

const formRef = ref(null)
const initFormData = async (id) => {
  const res = await requestUtil.get('user/action?id=' + id);
  form.value = res.data.msg;
}

watch(
    () => props.dialogVisible,
    async (visible) => {
      if (visible) {
        if (props.id !== -1) {
          await initFormData(props.id)
        } else {
          // formRef.value?.resetFields()
          form.value = {
            id: -1,
            username: '',
            password: '123456',
            status: 1,
            phone_number: '',
            email: '',
            remark: '',
          }
        }
      }
    },
    {immediate: true}
)

const emits = defineEmits(['update:modelValue', 'initTableData'])

const handleClose = () => {
  emits('update:modelValue', false)
  formRef.value.resetFields();
}
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = await requestUtil.post('user/save', form.value);
      let data = res.data;
      if (data.code === 200) {
        ElMessage.success('执行成功')
        formRef.value.resetFields();
        emits('initTableData');
        handleClose();
      } else {
        ElMessage.error(data.msg);
      }
    } else {
      console.log('fail')
    }
  })
}
</script>
